import cookies from './util.cookies';
import log from './util.log';
import db from './util.db';
import validate from './util.validate';
import date from './util.date';
import tool from './util.tool';
import token from './util.token';
import base64 from './util.base64';
import homePage from './util.homePage';
import downloadFile from './util.downloadFile';
import Setting from '@/setting';
import store from "@/store";
import { currentRouterBasePath } from "@/router";

const util = {
    cookies,
    log,
    db,
    validate,
    date,
    tool,
    token,
    base64,
    homePage,
    downloadFile
};

function tTitle(title) {
    if (window && window.$t) {
        if (title.indexOf('$t:') === 0) {
            return window.$t(title.split('$t:')[1]);
        } else {
            return title;
        }
    } else {
        return title;
    }
}

/**
 * @description 更改标题
 * @param {Object} title 标题
 * @param {Object} count 未读消息数提示（可视情况选择使用或不使用）
 */
util.title = function ({ title, count }) {
    title = tTitle(title);
    let titleSuffix = Setting.titleSuffix ? `-${Setting.titleSuffix}` : "";
    let fullTitle = title ? `${title}${titleSuffix}` : titleSuffix;

    if (count) fullTitle = `(${count}条消息)${fullTitle}`;
    window.document.title = fullTitle;
};

/**
 * @description 生成随机字符串
 * @param {Object} len 生成的字符串的长度，默认32
 */
util.randomStr = function (len = 32) {
    const $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    const maxPos = $chars.length;
    let str = '';
    for (let i = 0; i < len; i++) {
        str += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return str;
}

/**
 * @description 文件下载
 * @param {Object} blob 文件的二进制流
 * @param {Object} name 文件名，包含后缀名
 */
util.download = function (blob, name) {
    // 通过 blob 对象获取对应的 url
    const url = URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.download = name;
    a.style.display = 'none';
    a.href = url;
    document.body.appendChild(a);
    a.click();
    a.remove();
}

//在浏览器里打开新的页面
//href不包含origin和pathname
util.newPage = function(href="", blank=true){
    let origin = "";
    let pathname = "";
    if(window && window.location){
      origin = window.location.origin;
      if(Setting.routerMode === "history"){
        pathname = currentRouterBasePath;
      }else{
        pathname = window.location.pathname == "/" ? "" : window.location.pathname;
      }
    }
    href = origin + `${pathname}${(Setting.routerMode === 'hash' && href !="/") ? '#' : ''}${href}`.replace("//", "/");
    const dom = document.createElement('a')
    dom.href = href;
    dom.target = blank ? '_blank' : '_self';
    dom.style = {
      visibility: 'hidden',
      display: 'block'
    }
    document.body.appendChild(dom); // 新开页
    dom.click();
    dom.remove();
}

//判断是否是集团用户
util.isEnterprise = function(){
    let user = user = token.initToken() || {};
    if(user.cliqueId){
        return true;
    }
    if(!user.custId && !user.cliqueId){
        return true;
    }
    return false;
}

//解析url中的search参数并转换成对象
util.parseQueryString = function(url){
    var reg_url = /^[^\?]+\?([\w\W]+)$/,
         reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
         arr_url = reg_url.exec(url),
         ret = {};
     if (arr_url && arr_url[1]) {
         var str_para = arr_url[1],
             result;
         while ((result = reg_para.exec(str_para)) != null) {
             ret[result[1]] = result[2];
         }
     }
     return ret;
}

//将object中的属性转换成url中的参数
util.setQueryString = function(obj = {}){
    let str = JSON.stringify(obj);
    str = str.replace(/:/g,"=");
    str = str.replace(/"/g, '');
    str = str.replace(/,/g, '&');
    str = str.match(/\{([^)]*)\}/);
    return str[1] || "";
}

//缓存子用户的信息
util.cacheSubUserInfo = function(){
    const custId = "subCustId";
    const cliqueId = "subCliqueId";
    const groupCode = "subGroupCode";
    const customerType = "subCustomerType";
    let res = util.parseQueryString(window.location.href);
    if(res[custId] || res[cliqueId]){
        store.commit("admin/subUser/setUser", {
            custId: res[custId], 
            cliqueId: res[cliqueId],
            groupCode: res[groupCode],
            customerType: res[customerType]
        })
    }
}

function requestAnimation(task) {
    if ('requestAnimationFrame' in window) {
        return window.requestAnimationFrame(task);
    }

    setTimeout(task, 16);
}

export { requestAnimation };

export default util;
